﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using TechMadeira.Data.Classes;

namespace TechMadeira.Data
{
    public partial class Repository
    {
        static private Data mData = new Data();

        [Serializable,XmlRoot("Repository")]
        public class Data
        {
            public Data()
            {
                mData   = this;
                Objects = new List<ISemantic>();
            }

            [XmlIgnore]
            public List<ISemantic> Objects { get; private set; } 

            public IEnumerable<ISemantic> Semantics { get { return Objects; } }

            public void Append( ISemantic aSemantic )
            {
                if ( Objects.Contains( aSemantic ) ) return;
                Objects.Add( aSemantic );
            }

            public void Remove( ISemantic aSemantic )
            {
                if ( ! Objects.Contains( aSemantic ) ) return;
                Objects.Remove( aSemantic );
            }

            // Objects Hierarchies

            [XmlArray( ElementName = "Categories", Order = 1 )]
            public DependableCollection<ProductCategory> Categories 
            {
                get { return new DependableCollection<ProductCategory>( Objects ); }
            } 

            [XmlArray( ElementName = "Products", Order = 2 )]
            public DependableCollection<Product> Products 
            {
                get { return new DependableCollection<Product>( Objects ); }
            } 

            [XmlArray( ElementName = "Clients",Order = 3 )]
            public DependableCollection<Client> Clients 
            {
                get { return new DependableCollection<Client>( Objects ); }              
            } 

            [XmlArray( ElementName = "Orders",Order = 4 )]
            public DependableCollection<Order> Orders 
            {
                get { return new DependableCollection<Order>( Objects ); }              
            } 
        } 

        public void Load( string aConnection )
        {
            var formatter = new XmlSerializer( typeof(Data), GetTypes() );
            using ( Stream stream = File.OpenRead( aConnection ) )
            {
                mData = formatter.Deserialize( stream ) as Data;
            }
        }

        public void Save( string aConnection )
        {
            var formatter = new XmlSerializer( typeof (Data), GetTypes() );
            using ( Stream stream = new FileStream( aConnection, FileMode.Create, FileAccess.Write, FileShare.None ) )
            {
                formatter.Serialize( stream, mData );
            }
        }

    }
}
